package com.codermn.listner;

/**
 * @author jxau_scf
 * @date 2021/5/13 - 20:59
 */
import java.util.* ;
import javax.servlet.* ;
import javax.servlet.http.* ;

public class OnLineDemo
        implements ServletContextListener,HttpSessionListener,HttpSessionAttributeListener
{
    // 声明一个ServletContext对象
    private ServletContext application = null;
    @Override
    public void contextInitialized(ServletContextEvent sce)
    {
        // 容器初始化时，向application中存放一个空的容器
        this.application = sce.getServletContext() ;
        this.application.setAttribute("alluser",new HashSet()) ;
        this.application.setAttribute("allmap",new HashMap()) ;
        System.out.println("监听器初始化完成");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce)
    {}

    @Override
    public void sessionCreated(HttpSessionEvent se)
    {}
    @Override
    public void sessionDestroyed(HttpSessionEvent se)
    {
        // 将用户名称从列表中删除
        Set s = (Set)this.application.getAttribute("alluser") ;
        String value = (String)se.getSession().getAttribute("uname") ;
        s.remove(value) ;
        this.application.setAttribute("alluser",s) ;
        Map m = (Map)this.application.getAttribute("allmap") ;
        m.remove(value) ;
        this.application.setAttribute("allmap",m);
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent se)
    {
        // 如果登陆成功，则将用户名保存在列表之中
        Set s = (Set)this.application.getAttribute("alluser") ;
        s.add(se.getValue()) ;
        System.out.println("lintner在set集合中添加用户"+se.getValue());
        this.application.setAttribute("alluser",s);
        Map m = (Map)this.application.getAttribute("allmap");
        m.put(se.getValue(),se.getSession());
        this.application.setAttribute("allmap",m);
    }
    @Override
    public void attributeRemoved(HttpSessionBindingEvent se)
    {}
    @Override
    public void attributeReplaced(HttpSessionBindingEvent se)
    {
    }
}
/*
  <listener>
	<listener-class>cn.mldn.lxh.listener.OnLineDemo</listener-class>
  </listener>
*/